package com.juku2024.juku.dialog

import android.app.Dialog
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import com.juku2024.juku.R
import com.juku2024.juku.callback.OnNoDoubleClickListener
import com.juku2024.juku.model.UpdateModel
import com.juku2024.juku.tools.*

/**
 * 通知框
 */
class UpdateDialog(context: Context, private val updateModel: UpdateModel) : Dialog(context, R.style.CommonDialogStyle) {

    private lateinit var title: TextView
    private lateinit var tvContent: TextView
    private lateinit var btnAlwaysShow: TextView
    private lateinit var btnRight: TextView
    private lateinit var tvPercent: TextView
    private lateinit var pbUpdate: ProgressBar

    @Suppress("DEPRECATION")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_update)
        // 强升不能取消弹窗
        setCancelable(false)
        // 点击外部区域不能取消对话框
        setCanceledOnTouchOutside(false)
        btnAlwaysShow = findViewById(R.id.btnAlwaysShow)
        btnRight = findViewById(R.id.btnRight)
        title = findViewById(R.id.tvNoticeTitle)
        tvContent = findViewById(R.id.tvNoticeContent)
        pbUpdate = findViewById(R.id.pbUpdate)
        tvPercent = findViewById(R.id.tvPercent)


        // 设置标题
        title.text = updateModel.title?:"升级更新"
        // 设置按钮文本
        btnAlwaysShow.text = updateModel.btnTitle?:"升级"

        tvContent.movementMethod = ScrollingMovementMethod()
        // 开始响应点击事件
        tvContent.movementMethod = LinkMovementMethod.getInstance()
        // 加载富文本内容
        if (!TextUtils.isEmpty(updateModel.txt)) {
            val text = if (Build.VERSION.SDK_INT >= 24)
                Html.fromHtml(updateModel.txt, Html.FROM_HTML_MODE_COMPACT)
            else
                Html.fromHtml(updateModel.txt)
            tvContent.text = text
        }

        // 右侧按钮点击事件
        btnRight.setOnClickListener {
            dismiss()
            // 统计是否强制升级
            AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_USER_ACTION, "取消")
        }
        showUpdate()
    }

    private fun showUpdate() {
        val analysisForce = if (updateModel.foreceUpdate) {
            "强制升级"
        } else {
            "普通升级"
        }
        // 统计是否强制升级
        AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_FORCE, analysisForce)
        // 判断是否是强升
        if (updateModel.foreceUpdate) { // 强升
            // 强升没有"取消"按钮
            btnRight.visibility = View.GONE
            if (updateModel.downloadApk) { // app内部下载
                // 显示进度条
                pbUpdate.visibility = View.VISIBLE
                tvPercent.visibility = View.VISIBLE
            }
        } else {
            // 强升没有"取消"按钮
            btnRight.visibility = View.VISIBLE
            // 显示进度条
            pbUpdate.visibility = View.GONE
            tvPercent.visibility = View.GONE
        }

        btnAlwaysShow.setOnClickListener(object : OnNoDoubleClickListener {
            override fun onNoDoubleClick(v: View?) {
                super.onNoDoubleClick(v)
                if (TextUtils.isEmpty(updateModel.url)) {
                    dismiss()
                    return
                }
                // url是否是apk：0否 1是
                if (updateModel.downloadApk) { // 直接自动下载apk
                    DownloadApkTools.downloadApk(updateModel.url!!, {
                        val activity = AppUtils.findAppCompatActivity(context)
                        if (activity == null || activity.isFinishing || activity.isDestroyed) return@downloadApk
                        if (pbUpdate.visibility != View.VISIBLE) return@downloadApk
                        pbUpdate.post {
                            pbUpdate.progress = it
                            tvPercent.text = "$it%"
                        }
                    }, {
                        pbUpdate.post {
                            val activity = AppUtils.findAppCompatActivity(context)
                            if (activity == null || activity.isFinishing || activity.isDestroyed) return@post
                            DownloadApkTools.install(activity)
                        }
                    }, {
                        val activity = AppUtils.findAppCompatActivity(context)
                        if (activity == null || activity.isFinishing || activity.isDestroyed) return@downloadApk
                        if (pbUpdate.visibility != View.VISIBLE) return@downloadApk
                        pbUpdate.post {
                            tvPercent.text = "下载失败，请重试！"
                            btnAlwaysShow.text = "重试"
                        }
                    })
                    AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_USER_ACTION, "升级-下载Apk")
                } else { // 跳转web
                    // 统计是否强制升级
                    AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_USER_ACTION, "升级-GooglePlay")
                    AppUtils.toWeb(updateModel.url!!)
                }
                if (!updateModel.foreceUpdate) {
                    dismiss()
                }
            }
        })
    }

    override fun show() {
        super.show()
        // 统计展示弹窗的次数，应该跟升级成功次数一样
        AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_SHOW_DIALOG_TIMES)
    }

}